package cn.buildoncloud.labor.workermanapplet.business.modules.services.impl;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.ProjectService;
import cn.buildoncloud.labor.workermanapplet.business.modules.services.UserService;
import cn.buildoncloud.labor.workermanapplet.common.base.service.BaseServiceImpl;
import cn.buildoncloud.labor.workermanapplet.common.page.Pagination;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ProjectServiceImpl extends BaseServiceImpl<Map> implements ProjectService {
    public ProjectServiceImpl(Dao dao) {
        super(dao);
    }

    @Autowired
    private UserService userService;

    @Override
    public Map<String, Object> getUnitIdById(Long id) {
        StringBuilder sb = new StringBuilder("SELECT unit_id FROM `bi_project` WHERE id = @id");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("id", id);
        List<Record> result = this.list(sql);
        if (result.size() > 0){
            return result.get(0);
        }
        return null;
    }

    @Override
    public List<Record> listByCompany(String userId) {
        List<String> projectIds = userService.getScopeProjectIds(userId);
        if (projectIds.size() < 1) {
            return null;
        }
        Sql sql = Sqls.create("select concat(id,'') id , name ,concat(unit_id,'') unit_id from bi_project where id in (@ids) and approval_states != 2 and states = 1  order by start_date desc");
        sql.setParam("ids", projectIds.toArray());
        List<Record> list = this.list(sql);

        return list;

    }

    @Override
    public Pagination listByUser(String userId, Integer pageNumber, Integer pageSize){
        List<String> projectIds = userService.getScopeProjectIds(userId);
        if (projectIds.size() < 1) {
            return null;
        }
        StringBuffer stringSql = new StringBuffer("select concat(b_p.id,'') id , b_p.name name,concat(b_p.unit_id,'') unit_id,b_p.states states,CONCAT(start_date, '至',completion_date) intervalDate ,b_p.address address,s_p_y.name typeName ");
        stringSql.append("from bi_project b_p left join sys_project_type s_p_y on s_p_y.id = project_type_id $condition ");
        Sql sql = Sqls.create(stringSql.toString());
        Cnd cnd = Cnd.where("b_p.approval_states","=",1)
                .and("b_p.states","!=",2)
                .and("b_p.id","in",projectIds);
        cnd.desc("b_p.start_date");
        sql.setCondition(cnd);

        return this.listPage(pageNumber,pageSize,sql);
    }


}
